package com.backend.demo1.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.backend.demo1.annotations.JwtRequired;
import com.backend.demo1.config.ApiResponse;
import com.backend.demo1.models.Member;
import com.backend.demo1.services.AuthService;
import com.backend.demo1.services.MemberService;
import com.backend.demo1.utils.JwtUtil;

@RestController
@RequestMapping("/api/members")
public class MemberController {

    @Autowired
    private MemberService memberService; 

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtUtil jwtUtil;

    @JwtRequired
    // 添加会员
    @PostMapping
    public ResponseEntity<ApiResponse<Void>> addMember( 
        @RequestHeader("Authorization") String authorizationHeader,
        @RequestBody Member member) {
        try {
            String token = authorizationHeader.substring(6); // 去掉 "Token " 前缀
            String username = jwtUtil.extractUsername(token);
            Long userId = authService.findUserIdByUsername(username);

            if(userId != null){
                // 检查是否已存在该会员（通过 userId）
                boolean exists = memberService.existsByUserId(userId);
                if (exists) {
                    return ResponseEntity.status(HttpStatus.CONFLICT) // 409 Conflict
                            .body(ApiResponse.error(409, "已申请会员"));
                }
                member.setUserId(userId);
                memberService.insert(member);
                return ResponseEntity.status(HttpStatus.CREATED) // 201 Created
                        .body(ApiResponse.success("会员增加成功",null));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST) // 400 Bad Request
                        .body(ApiResponse.notFound( "用户不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) // 500
                    .body(ApiResponse.internalServerError(e.getMessage()));
        }
    }

    // 根据 ID 查找会员
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Member>> getMember(@PathVariable Long id) {
        try {
            Member member = memberService.findById(id);
            if (member != null) {
                return ResponseEntity.ok() // 200 OK
                        .body(ApiResponse.success(member));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND) // 404 Not Found
                        .body(ApiResponse.error(404, "会员不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) // 500
                    .body(ApiResponse.internalServerError(e.getMessage()));
        }
    }

    // 获取所有会员
    @GetMapping
    public ResponseEntity<ApiResponse<List<Member>>> getAllMembers() {
        try {
            List<Member> members = memberService.findAll();
            return ResponseEntity.ok() // 200 OK
                    .body(ApiResponse.success(members));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) // 500
                    .body(ApiResponse.internalServerError(e.getMessage()));
        }
    }

    @JwtRequired
    // 更新会员信息
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> updateMember(@PathVariable Long id, @RequestBody Member member) {
        try {
            // 确保更新时 ID 一致
            if (member.getUserId() == null || !member.getUserId().equals(id)) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST) // 400 Bad Request
                        .body(ApiResponse.notFound( "ID 不匹配"));
            }
            memberService.update(member);
            return ResponseEntity.ok() // 200 OK
                    .body(ApiResponse.success("会员更新成功",null));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) // 500
                    .body(ApiResponse.internalServerError(e.getMessage()));
        }
    }

    @JwtRequired
    // 删除会员
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteMember(@PathVariable Long id) {
        try {
            memberService.deleteById(id);
            return ResponseEntity.status(HttpStatus.NO_CONTENT) // 204 No Content
                    .body(ApiResponse.success("会员删除成功",null));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) // 500
                    .body(ApiResponse.internalServerError(e.getMessage()));
        }
    }
}